/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.http.HttpSession;

import edu.cmu.lti.sepia.data.db.LogDAO;
import edu.cmu.lti.sepia.data.db.SQL;
import edu.cmu.lti.sepia.infra.system.model.Log;

public class Logger {
	
  //Log events:
  //DOWNLOAD FILE, UPLOAD FILE, 
  
	private final static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Logger.class);
	
	public static String log( SQL sql, HttpSession session, String logEvent, String detail ) {
		SessionUtil s = new SessionUtil(session);
		String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
		int taskId = s.readInt("taskId", 0);
		int userId = s.readInt("userId", 0);
		String host = s.readString("host", "");
		Log log = new Log(0, date, taskId, userId, host, logEvent, detail);
		try {
			LogDAO.addLog(sql, log);
		} catch (Exception e) {
			return ExceptionUtil.exceptionToString(e);
		}
		logger.info( "User activity: "+logEvent+" ("+detail+") by userId "+userId+" ("+host+") @ taskId "+taskId );
		
		return printLog(session, logEvent, detail);
	}
	

	// to be deleted? only used by legacy code
	public static String printLog( HttpSession session, String logEvent, String detail  ) {
		return logEvent +" " + detail;
	}
}
